/* 
    请求接口
*/

export const ApiClient = new (class {
    API = {
        // 卡片管理
        card: { url: "/card/get", method: 'get' },
        cards: { url: "/card/gets", method: 'get' },
        update: { url: "/card/update", method: 'put' },
        create: { url: "/card/create", method: 'post' },
        delete: { url: "/card/delete", method: 'delete' },
        // 用户鉴权
        login: { url: "/login", method: "post" },
    }

    constructor(baseURL) {
        this.baseURL = baseURL

        // 动态创建方法
        Object.keys(this.API).forEach(key => {
            this[key] = async (data, pathParam = "") => {
                const { url, method } = this.API[key]
                const fullPath = `${url}/${pathParam}`
                return await this.request(fullPath, method, data)
            }
        })
    }

    async request (url, method, data = null) {
        let fullURL = this.baseURL + url
        const options = {
            method,
            headers: {
                'Content-Type': 'application/json',
            },
        }

        const isMethod = ['get', 'delete'].includes(method.toLowerCase())


        // 只在非 GET 或 DELETE 方法时设置请求体
        if (data && !isMethod) {
            if (url.includes('login')) {
                let matchUrl = fullURL.match(/(.*):(\d+)(\/.*)/)
                fullURL = `${matchUrl[1]}:${data.port}/login`

                delete data.port

                const formData = new URLSearchParams()
                for (const key in data) {
                    formData.append(key, data[key])
                }

                options.headers["Content-Type"] = 'application/x-www-form-urlencoded'
                options.body = formData
            } else {
                options.body = JSON.stringify(data)
            }
        }

        try {
            const response = await fetch(fullURL, options)
            if (!response.ok) {
                throw new Error(`Request failed with status ${response.status}`)
            }

            // 根据响应类型处理
            const conLength = response.headers.get('Content-Length')
            if (options.headers["Content-Type"] === response.headers.get('Content-Type')
                || conLength !== '0'
                || url.includes('login')
            ) {
                console.log(response)
                return await response.json()
            }
            return response

        } catch (error) {
            console.error('API request error:', error.message)
        }
    }
})("http://localhost:50020/api/v1")



// ApiClient.login({ username: 'root', passwd: '123456', port: 50010 })
//     .then(resp => console.log(resp))
//     .catch(err => console.error(err))

// 单条
// api.card({}, "-2041153929").then(resp => console.log(resp))

// 全部
// api.cards().then(resp => console.log(resp))

// // 删除
// api.delete({}, "-780493967").then(resp => console.log(`删除成功: ${resp}`))

// 创建 => { id: 148195236, title: 'Hello World', content: '' }
// api.create({ title: "Hello World", content: "不知道Leisure" })
//     .then(resp => console.log(resp))


// 更新 => { id: 148195236, title: 'Hello World', content: 'Hello World' }
// api.update({ title: "居然没返回信息!", content: "真是离谱" }, "-1738447068")
//     .then(resp => resp.text())
//     .then(rq => {
//         console.log(rq)
//     })

// setTimeout(
//     () => (api.cards().then(resp => console.log(resp))),
//     2000,
// )